/*
 * 暂不支持下面格式的歌词
 * [01:02.97][01:53.50][02:20.60]虽然闭着眼假装听不到
 */
var Lyric = (function(){
	var regType = /([^:]+):(.*)/;
	var lyricTplFun,
		timeItems,
		timeLines,
		boxTop;
	var curIndex=-1;
	function play(url){
		if(!rootDirEntry) return;
		if(!lyricTplFun){
			Lyric.init();
		}
		rootDirEntry.getFile(url, {}, function(fileEntry) {

		    // Get a File object representing the file,
		    // then use FileReader to read its contents.
		    fileEntry.file(function(file) {
				var reader = new FileReader();

				reader.onloadend = function(e) {
					var lyricText = this.result,
						title,
						artist;
					timeLines = [];
					lyricText.replace(/\[([^\]]+)\]([^\[]*)/g, function(_$, _$1, _$2){
						if(!regType.test(_$1.trim())) return;
						var type = RegExp.$1.trim(),
							content = RegExp.$2.trim();
						if(type=="ar")
							artist = content.encode4Html();
						else if(type=="ti")
							title = content.encode4Html();
						else if(/^\d+$/.test(type)){
							var time = parseInt(type)*60+parseFloat(content);
							
							timeLines.push({
								time: time,
								text: _$2.encode4Html()
							})
						}
					});
					timeLines.sort(function(a,b){
						return a.time-b.time;
					});

					var html = lyricTplFun({
						title: title,
						artist: artist,
						timeLines: timeLines
					});
					$('.play-content-lyric').html(html);

					timeItems = $('.lyric-item');
					timeItems.forEach(function(item, index){
						timeLines[index].pos = Math.floor($(item).position().top);
					});
				};

				reader.readAsText(file);
		    }, function(e){
		    	console.log('lyric error 2');
		    	console.log(e);
		    });

		}, function(e){
	    	console.log('lyric error 1');
	    	console.log(e);
	    });		
	}

	function move(time){
		if(!timeLines) return;
		if(!timeLines[curIndex+1]) return;
		var item = timeLines[curIndex+1];
		if(time > item.time){
			$('.lyric-panel').css('top', -item.pos+'px');
			timeItems.eq(curIndex).removeClass('lyric-cur');
			timeItems.eq(curIndex+1).addClass('lyric-cur');
			curIndex++;
		}
	}

	function init(){
		lyricTplFun = $('#lyricTpl').html().tmpl();
		boxTop = $('.play-content-lyric')
	}
	return {
		play: play,
		init: init,
		move: move
	};
})();